package com.amos.muexamclient.sys.service.impl;

import com.amos.exception.BizExceptionEnum;
import com.amos.muexamclient.security.service.SysPermissionService;
import com.amos.muexamclient.sys.service.SysUserService;
import com.amos.muexamclient.sys.service.dto.LoginUser;
import com.amos.muexamclient.sys.service.dto.SysUserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * Copyright © 2018 嘉源锐信. All rights reserved.
 *
 * @Project: mu-exam
 * @ClassName: UserDetailsServiceImpl
 * @Package: com.amos.muexamclient.sys.service.impl
 * @author: zhuqb
 * @Description:
 * @date: 2020/3/24 0024 下午 16:47
 * @Version: V1.0
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    SysUserService userService;
    @Autowired
    SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUserDTO userDTO = userService.getByUsername(username);
        BizExceptionEnum.NOT_NULL.definedMsg("登录用户:" + username + " 不存在");
        if (!userDTO.getStatus()) {
            BizExceptionEnum.DEFINED_EXCEPTION.definedMsg("对不起，您的账号：" + username + " 已停用");
        }
        return createLoginUser(userDTO);
    }

    /**
     * @param user
     * @return
     */
    public UserDetails createLoginUser(SysUserDTO user) {
        return new LoginUser(user, permissionService.getMenuPermission(user));
    }
}
